package br.com.pnfp.web.view.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.beanutils.BeanUtils;

import br.com.pnfp.web.model.enums.UF;

public class ComboUFTag extends TagSupport {
	
	private static final long serialVersionUID = -6707142814661922021L;
	
	private String name;
	private String onchange;
	
	@Override
	public int doStartTag() throws JspException {
		
		JspWriter out = pageContext.getOut();
		
		String value = "";
		try {
			Object objForm = pageContext.getRequest().getAttribute("org.apache.struts.taglib.html.BEAN");
			value = BeanUtils.getProperty(objForm, getName());
		} catch(Exception e) {}
		
		StringBuilder combo = new StringBuilder();
		combo.append("<select id='").append(getName()).append("' name='").append(getName()).append("' ");
		if(getOnchange() != null && !getOnchange().equals("")) {
			combo.append("onchange=\"").append(getOnchange()).append("\" ");
		}
		combo.append("title='UF'>");
		combo.append("<option value=''>Selecione...</option>");
		for(UF uf : UF.values()) {
			combo.append("<option value='").append(uf.name()).append("'");
			if(value != null && !value.equals("") && uf.name().equals(value)) {
				combo.append(" selected ");
			}
			combo.append(">").append(uf.name()).append("</option>");
		}
		combo.append("</select>");
		
		try {
			out.print(combo.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return super.doStartTag();
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getOnchange() {
		return onchange;
	}
	public void setOnchange(String onchange) {
		this.onchange = onchange;
	}

}
